<script setup>
import SchedulingFrame from '../components/SchedulingFrame.vue';
import { ref, onBeforeMount } from 'vue'
import { ElMessageBox } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue' // codeMirror 从DialogYaml组件引用
import { storeToRefs } from 'pinia'
import { useItem } from '../../store';
import { createDaemonSetHandler as createItem, updateDaemonSetHandler as updateItem } from '../../api/daemonset.js';
import { obj2Yaml } from '../../utils/utils';
import StringOrNumber from '../components/StringOrNumber.vue';
import { useRouter } from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  resourceType: {
    type: String,
    default: 'DaemonSet'
  }
})
const useItemer = useItem()
const showDetail = ref(false)
const yamlContent = ref('')

const submitRollback = (msg) => {
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '继续编辑',
      type: 'success',
      draggable: true,
    }
  ).then(() => {
    router.replace({
      path: '/daemonset/list',
      query: {
        clusterId: useItemer.clusterId,
        namespace: useItemer.namespace
      }
    })
  }).catch(() => {
    console.info("继续编辑")
    router.replace({
      path: '/daemonset/edit',
      query: {
        clusterId: useItemer.clusterId,
        namespace: useItemer.namespace,
        name: useItemer.item.metadata.name,
        method: "Update"
      }
    })
  })
}
const submit = (tag, autoCreateService) => {
  const item = {
      'apiVersion': 'apps/v1',
      'kind': 'DaemonSet',
      'metadata': useItemer.item.metadata,
      'spec': useItemer.item.spec
    }
  if(tag == 'yaml') { // json转yaml
    const yamlData = obj2Yaml(item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: useItemer.clusterId,
      namespace: useItemer.namespace,
      item: item,
      autoCreateService // 自动创建service Boolean
    }
    if (props.method != 'Update') {
      createItem(postData).then((response) => {
        submitRollback(response.data.message)
      })
    } else {
      updateItem(postData).then((response) => {
        console.log(props.method)
        submitRollback(response.data.message)
      })
    }
  }
}
// 返回更新方式的类型
const StrategyType = [
  {
    value: "RollingUpdate",
    label: "滚动更新"
  },
  {
    value: "OnDelete",
    label: "手动删除后重建"
  }
]
// 变更更新方式
const strategyChanged = (val) => {
    console.log("更新方式:", val)
    // 当更新方式为Recreate的时候，删除rollingUpdate
    if (val == "OnDelete") {
        delete useItemer.item.spec.updateStrategy.rollingUpdate
    } else if (val == "RollingUpdate") {
      useItemer.item.spec.updateStrategy.rollingUpdate = {
          maxSurge: "25%",
          maxUnavailable: "25%"
      }
    }
}
onBeforeMount(() => {
  if (props.method == 'Create') {
    useItemer.item.spec.updateStrategy = {
      type: "RollingUpdate",
      rollingUpdate: {
        maxSurge: "25%",
        maxUnavailable: "25%"
      }
    }
  }
  delete useItemer.item.spec.replicas // 删除副本数字段
})
const { clusterId, namespace, item } = storeToRefs(useItem())
</script>

<template>
  <SchedulingFrame @submit="submit" :method="props.method" :resource-type="props.resourceType">
    <template #strategy>
      <el-col :span="6">
        <el-form-item label="更新方式" prop="spec.updateStrategy">
            <el-select v-model="item.spec.updateStrategy.type" style="width:180px" @change="strategyChanged" placeholder="选择更新方式">
                <el-option
                v-for="s in StrategyType"
                :key="s.value"
                :label="s.label"
                :value="s.value"
                >
                </el-option>
            </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
          <el-form-item title='值可以是绝对数字(例如:5)或所需 Pod 的百分比(例如:10%)' label="最大不可用" prop="" v-if="item.spec.updateStrategy.type=='RollingUpdate'">
              <StringOrNumber input-width="150px" v-model:data="item.spec.updateStrategy.rollingUpdate.maxUnavailable" placeholder="最大不可用"></StringOrNumber>
          </el-form-item>
      </el-col>
      <el-col :span="6">
          <el-form-item title='值可以是绝对数字(例如:5)或所需 Pod 的百分比(例如:10%)' label="可超出最大值" prop="" v-if="item.spec.updateStrategy.type=='RollingUpdate'">
              <StringOrNumber input-width="150px" v-model:data="item.spec.updateStrategy.rollingUpdate.maxSurge" placeholder="可超出最大值"></StringOrNumber>
          </el-form-item>
      </el-col>
    </template>
  </SchedulingFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val) => { showDetail = val }"
  >
  </DialogYaml>
</template>

<style scoped>
</style>
